package com.itfreer.arcgis.layer;

import android.graphics.Color;

import com.esri.arcgisruntime.data.TileCache;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.itfreer.arcgis.utils.FeatureTableUtils;
import com.itfreer.arcgis.utils.LayerUtils;
import com.itfreer.arcgis.utils.MapUtils;
import com.itfreer.file.path.FileUpload;
import com.itfreer.gis.config.BaseMapService;
import com.itfreer.gis.config.entity.BaseMapEntity;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.gis.datasyn.sub.ProjectService;
import com.itfreer.utils.common.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 图层加载器
 */
public class LayerLoader {

    public static final LayerLoader instance = new LayerLoader();
    private LayerLoader() {
    }

    private HashMap<FeatureLayer, ProjectEntity> configCache = new HashMap<>();
    private boolean mapIsLoad = false;

    public boolean getMapIsLoad(){
        return mapIsLoad;
    }

    public void setMapIsLoad(boolean mapIsLoad){
        this.mapIsLoad = mapIsLoad;
    }

    /**
     * 更新配置
     * @param layer
     * @param config
     */
    public void updateConfig(FeatureLayer layer, ProjectEntity config){
        if(configCache.containsKey(layer)){
            configCache.put(layer, config);
        }
    }

    /**
     * 根据FeatureLayer获取图层配置信息
     * @param layer
     * @return
     */
    public ProjectEntity getConfig(FeatureLayer layer) {
        if(configCache.containsKey(layer)){
            return configCache.get(layer);
        } else {
            return null;
        }
    }

    /***
     * 重新加载图层
     */
    public void loadLayer(MapView mMapView){
        if(mapIsLoad){
            return;
        }

        loadTPK(mMapView);
        loadShapeLayer(mMapView);
    }

    /**
     * 加载tpk影像底图文件
     */
    private void loadTPK(MapView mMapView){
        List<BaseMapEntity> baseMaps = BaseMapService.instance.getEntitys();
        if(baseMaps==null || baseMaps.size()<=0){
            return;
        }

        for(BaseMapEntity item : baseMaps){
            String path = item.getPath();
            String[] paths = path.split(":");
            String buckt = paths[0];
            String key = paths[1];
            String tpkPath = FileUpload.instance.getFile(buckt, key);
            File tpkFile = new File(tpkPath);
            if(tpkFile.exists()){
                TileCache titleCache = new TileCache(tpkPath);
                ArcGISTiledLayer arcGISTiledLayer = new ArcGISTiledLayer(titleCache);
                Basemap basemap = new Basemap(arcGISTiledLayer);
                ArcGISMap arcGISMap = new ArcGISMap(basemap);
                mMapView.setMap(arcGISMap);
            }
        }
    }

    /**
     * 加载矢量数据
     * @param mMapView
     */
    private void loadShapeLayer(MapView mMapView){
        //获取图层对象
        MapUtils.ClearMapLayer(mMapView);
        List<ProjectEntity> layers = ProjectService.instance.getProject();
        configCache.clear();
        mapIsLoad = true;

        if(layers != null && layers.size() >= 1){
            for (int i = layers.size() -1;i >= 0; i--){
                //获取文件路径
                // plupload:20180815/o_1cku6jsqb93s13t5nl886nce4a.zip:JC_SLZY.zip
                String path = layers.get(i).getPath();
                String[] paths = path.split(":");
                String buckt = paths[0];
                String key = paths[1];
                String fName = paths[2];
                fName = fName.replace(".zip", "").replace(".ZIP", "");
                String folderPath = FileUpload.instance.getDir(buckt, key) + "/" + fName + "/" + fName + ".shp";
                //依次加载本地shp文件
                loadShapeFile(mMapView, folderPath, layers.get(i), true);
            }
        }
    }

    /**
     * 加载本地shape数据
     * @param path 路径
     */
    private void loadShapeFile(MapView mMapView, String path, ProjectEntity config, Boolean extend) {
        if (!path.endsWith(".shp")) {
            return;
        }

        Boolean canShow = config.getShow();
        FeatureLayer featureLayer = LayerUtils.CreateFeatureLayerFormTable(FeatureTableUtils.GetFeatureTableFormShape(path));
        if (featureLayer == null) {
            return;
        }

        //获取渲染配置
        try{
            String redStr = config.getRenderer();
            if(!StringUtils.IsNullOrEmpty(redStr)){
                //添加渲染
                LayerUtils.AddRenderer(featureLayer,redStr);
            }

            //获取标注配置
            String labelStr = config.getLabel();
            //获取标注字典参数
            String labelParaStr =  config.getLabelPara();
            if(!StringUtils.IsNullOrEmpty(labelStr)){
                if(StringUtils.IsNullOrEmpty(labelParaStr)){
                    //简单添加标注
                    LayerUtils.AddFeatureLayerLabel(featureLayer, labelStr);
                }else{
                    //先翻译字典，再添加标注
                    labelStr = LayerUtils.replaceDicnaryValue(labelParaStr,labelStr);
                    LayerUtils.AddFeatureLayerLabel(featureLayer, labelStr);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置是否显示
        if (featureLayer != null && featureLayer.canChangeVisibility()) {
            featureLayer.setVisible(canShow);
        }
        //设置图层比例尺显示大小
        if(config.getMaxScale()!=null && config.getMaxScale()>0){
            featureLayer.setMaxScale(config.getMaxScale());
        }
        if(config.getMinScale()!=null && config.getMinScale()>0){
            featureLayer.setMinScale(config.getMinScale());
        }

        featureLayer.setSelectionColor(Color.YELLOW);
        featureLayer.setSelectionWidth(10);

        MapUtils.AddFeatureLayer(mMapView, featureLayer, extend, "");
        configCache.put(featureLayer, config);
    }
}